<?php 

namespace App\Repositories;
use Illuminate\Container\Container as App;
use App\Repositories\DepartmentRepository;
use App\Repositories\OrderRepository;
use App\Repositories\CustomerRepository;
use App\Repositories\RenewRepository;

class UserRepository extends Repository 
{
    public function __construct(App $app, DepartmentRepository $department) {
        parent::__construct($app); 
        $this->department = $department;
    }

    public function model() {
        return 'App\Models\User';
    }

    public function designerSelect()
    {
    	return $this->model->designer()->lists('name', 'id');
    }

    public function designerSelectStatus()
    {
        return $this->model->designer()->where('status', 1)->lists('name', 'id');
    }

    public function designers()
    {
        return $this->model->designer()->get();
    }

    public function salerSelect($where=[])
    {
        $model = $this->model;

        if (!empty($where)) {
            foreach ($where as $key => $value) {
                $model = $this->model->where($key, $value);
            }
        }

    	return $model->saler()->lists('name', 'id');
    }

    public function getSalersAll()
    {
        return $this->model->saler()->select('id', 'name')->get()->keyBy('id');
    }

    public function getSalers()
    {
        return $this->model->saler()->get();
    }

    public function getSalersByDepartment()
    {
        $data = $this->getSalers();

        $temp = array();
        if (!$data->isEmpty()) {
            foreach ($data as $key => $value) {
                $temp[$value->department_id][] = $value->toArray();
            }
        }
        return $temp;
    }

    public function getUidsByDepartments($departments)
    {
        return $this->model->whereIn('department_id', (array)$departments)->lists('id');
    }

    // 用户分页
    public function paginateList($where, $page = 15)
    {
        $model = $this->model->with('group', 'department');

        $where = $where->filter(function ($item) { return $item; });

        if ($where->has('name')) {
            $model->where('name', 'like', '%'.$where->get('name').'%');
        }

        if ($where->get('department_id')) {
            $model->where('department_id', $where->get('department_id'));
        } elseif ($where->get('region_id')) {
             $model->where('region_id', $where->get('region_id'));
        }

        return $model->paginate($page);
    }

    // 人员数量-按照用户组分组
    public function getCountsGroup()
    {
        return $this->model->select(\DB::raw('gid, count(*) as count'))->groupBy('gid')->get();
    }

    // 统计用户数量 - 按照区域
    public function getCountByRegionLists()
    {
        return $this->model->select(\DB::raw('region_id, count(*) as count'))->groupBy('region_id')->lists('count', 'region_id');
    }

    // 统计用户数量 - 按照部门
    public function getCountByDepartmentLists()
    {
        return $this->model->select(\DB::raw('department_id, count(*) as count'))->groupBy('department_id')->lists('count', 'department_id'); 
    }

    // 判断内容拥有者
    public function owner($uid, $loginUser, $msg = '您没有权限查看该内容。')
    {
        $level = $loginUser->group->level;

        if ($level == 3) {
            // 业务员
            if ($uid != $loginUser->id) {
                return abort(403, $msg);
            }
        } elseif ($level == 4) {
            // 业务经理
            $uids = $this->getUidsByDepartments($loginUser->department->id);

            if (!$uids->contains($uid)) {
                return abort(403, $msg);
            }
        } elseif ($level == 8) {
            // 业务总监
            $result = $this->findWhere([
                'id' => $uid,
                'region_id' => $loginUser->region_id,
            ]);

            return $result->isEmpty() && abort(403, $msg);
        }

        return true;
    }

    public function checkUserDestroy($id)
    {
        $order = app(OrderRepository::class);
        $customer = app(CustomerRepository::class);
        $renew = app(RenewRepository::class);

        // 订单数量
        $orderCounts = $order->getCountWhere([['saler_id', $id]]);
        // 客户数量
        $customercounts = $customer->getCountsBySaler($id);
        // 续费数量
        $renewCounts = $renew->getCountsByUser($id);

        //如果是技术，则判断是否有负责的订单
        $designerCounts = $order->getCountsByDesigner($id);

        if ($orderCounts + $customercounts + $renewCounts + $designerCounts > 0) {
            return false;
        }

        return true;
    }

    public function getRegionsByUids($uids)
    {
        return $this->model->whereIn('id', $uids)->groupBy('region_id')->lists('region_id');
    }

    // 检查一个区域或者一个部门的人员个数
    public function getCountByDepartment($id)
    {
        $department = $this->department->find($id);

        if ($department->pid == 0) {
            return $this->model->where('region_id', $department->id)->count();   // 区域
        }

        return $this->model->where('department_id', $department->id)->count();   // 部门
    }

    // 得到每个设计师组的ID集合
    public function getUsersByTeam()
    {
        return $this->model->select(\DB::raw('GROUP_CONCAT(id) as team_ids, team'))->where('team', '>', 0)
                           ->groupBy('team')->lists('team_ids', 'team');
    }
}